import { createRouter, createWebHistory } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { ElMessage } from 'element-plus'

//导入组件
import LoginVue from '@/views/Login.vue'
import LayoutVue from '@/views/Layout.vue'

import UserAvatarVue from '@/views/user/UserAvatar.vue'
import UserInfoVue from '@/views/user/UserInfo.vue'
import UserResetPasswordVue from '@/views/user/UserResetPassword.vue'
import LessonCategoryVue from '@/views/lesson/LessonCategory.vue'
import LessonManageVue from '@/views/lesson/LessonManage.vue'
import HomeVue from '@/views/Home.vue'
import SearchResults from '@/views/SearchResults.vue';
import ChatVue from '@/views/ai/Chat.vue'
import FriendsVue from '@/views/friend/Friends.vue'
import Talk from '@/views/friend/Talk.vue'
import TeacherApproval from '@/views/admin/TeacherApproval.vue'
import UserManagement from '@/views/admin/UserManagement.vue'
import TeacherCertification from '@/views/teacher/TeacherCertification.vue'
import TutoringList from '@/views/tutoring/TutoringList.vue'
import TutoringPublish from '@/views/tutoring/TutoringPublish.vue'
import TutoringManage from '@/views/tutoring/TutoringManage.vue'
import TutoringBooking from '@/views/tutoring/TutoringBooking.vue'
import BannerManage from '@/views/admin/BannerManage.vue'

//定义路由关系
const routes = [
    { path: '/login', component: LoginVue },
    { path: '/home', component: HomeVue },
    {
        path: '/search-results', // 搜索结果页面的路由
        name: 'SearchResults',
        component: SearchResults,
      },
  
    {
        path: '/', 
        component: LayoutVue,
        meta: { requiresAuth: true },
        children:[
            { 
                path: '/user/info', 
                component: UserInfoVue,
                meta: { roles: [0, 1, 2] }  // 所有角色都可访问
            },
            { 
                path: '/user/avatar', 
                component: UserAvatarVue,
                meta: { roles: [0, 1, 2] }
            },
            { 
                path: '/user/resetPassword', 
                component: UserResetPasswordVue,
                meta: { roles: [0, 1, 2] }
            },
            { 
                path:'/lesson/category', 
                component: LessonCategoryVue,
                meta: { 
                    roles: [2],  // 只允许管理员访问
                    title: '课程分类管理',  // 添加标题用于菜单显示
                    icon: 'Menu',  // 添加图标
                    isAdmin: true  // 标记为管理员专属功能
                }
            },
            { 
                path:'/lesson/manage', 
                component: LessonManageVue,
                meta: { 
                    roles: [0, 1],  // 只允许学生和教师访问
                    title: '课程管理',  // 添加标题用于菜单显示
                    icon: 'Document',  // 添加图标
                    requiresTeacherApproval: true  // 教师需要审核通过
                }
            },
            { 
                path:'/lesson/list', 
                component: () => import('@/views/lesson/LessonList.vue'),
                meta: { 
                    roles: [0, 1, 2],  // 所有角色都可以访问
                    title: '课程列表'  // 添加标题用于菜单显示
                }
            },
            { 
                path:'/stream', 
                component: ChatVue,
                meta: { roles: [0, 1, 2] }
            },
            { 
                path:'/friend', 
                component: FriendsVue,
                meta: { roles: [0, 1, 2] }
            },
            { 
                path:'/feedback',
                component: () => import('@/views/feedback/FeedbackPage.vue'),
                meta: { 
                    roles: [0, 1, 2],
                    title: '留言反馈'
                }
            },
            { 
                path:'/cm', 
                component: Talk,
                meta: { 
                    roles: [0, 1, 2],
                    title: '聊天'
                }
            },
            {
                path: '/admin/teachers',
                component: TeacherApproval,
                meta: { 
                    roles: [2],
                    isAdmin: true
                }
            },
            {
                path: '/admin/users',
                component: UserManagement,
                meta: { 
                    roles: [2],
                    isAdmin: true
                }
            },
            {
                path: '/teacher/certification',
                component: TeacherCertification,
                meta: { 
                    roles: [0, 1],  // 允许学生角色访问（实际上是临时降级的教师）
                    requiresAuth: true
                }
            },
            {
                path: '/tutoring/list',
                component: TutoringList,
                meta: { roles: [0, 1, 2] }
            },
            {
                path: '/tutoring/publish',
                component: TutoringPublish,
                meta: { 
                    roles: [1],
                    requiresTeacherApproval: true
                }
            },
            {
                path: '/tutoring/manage',
                component: TutoringManage,
                meta: { 
                    roles: [1],
                    requiresTeacherApproval: true
                }
            },
            {
                path: '/tutoring/booking',
                component: TutoringBooking,
                meta: { roles: [0, 1] }
            },
            {
                path: '/teacher/schedule',
                name: 'TeacherSchedule',
                component: () => import('@/views/tutoring/TeacherSchedule.vue'),
                meta: { requiresAuth: true, roles: [1] }
            },
            {
                path: '/student/schedule',
                name: 'StudentSchedule',
                component: () => import('@/views/tutoring/StudentSchedule.vue'),
                meta: { requiresAuth: true, roles: [0] }
            },
            {
                path: '/student/pending-schedule',
                name: 'StudentPendingSchedule',
                component: () => import('@/views/tutoring/StudentPendingSchedule.vue'),
                meta: { requiresAuth: true, roles: [0] }
            },
            {
                path: '/homework/teacher',
                name: 'TeacherHomework',
                component: () => import('@/views/homework/TeacherHomework.vue'),
                meta: {
                    requiresAuth: true,
                    roles: [1],  // 改为数字1表示教师角色
                    requiresTeacherApproval: true // 需要教师认证通过
                }
            },
            {
                path: '/homework/student',
                name: 'StudentHomework',
                component: () => import('@/views/homework/StudentHomework.vue'),
                meta: {
                    requiresAuth: true,
                    roles: [0]  // 改为数字0表示学生角色
                }
            },
            {
                path: '/student/mistake-book',
                name: 'MistakeBook',
                component: () => import('@/views/mistake/MistakeBook.vue'),
                meta: {
                    requiresAuth: true,
                    role: 0 // 只允许学生访问
                }
            },
            {
                path: '/teacher/knowledge-points',
                name: 'KnowledgePoints',
                component: () => import('@/views/teacher/KnowledgePoints.vue'),
                meta: {
                    requiresAuth: true,
                    role: 1
                }
            },
            {
                path: '/admin/banner',
                component: BannerManage,
                meta: {
                    requiresAuth: true,
                    requiresAdmin: true
                }
            },
            {
                path: '/admin/announcement',
                component: () => import('@/views/admin/AnnouncementManage.vue'),
                meta: { requiresAuth: true, roles: [2] }
            },
            {
                path: '/admin/feedback',
                component: () => import('@/views/admin/FeedbackManage.vue'),
                meta: { 
                    roles: [2],
                    isAdmin: true,
                    title: '反馈管理'
                }
            },
            {
                path: '/admin/lesson',
                component: () => import('@/views/admin/LessonManage.vue'),
                meta: { 
                    roles: [2],
                    isAdmin: true,
                    title: '网课管理'
                }
            },
            {
                path: '/admin/tutoring',
                component: () => import('@/views/admin/TutoringAudit.vue'),
                meta: { 
                    roles: [2],
                    isAdmin: true,
                    title: '家教审核'
                }
            }
        ]  
    },
    {
        path: '/payment',
        component: LayoutVue,
        meta: { requiresAuth: true },
        children: [
            {
                path: 'create',
                name: 'PaymentCreate',
                component: () => import('@/views/payment/Create.vue'),
                meta: { requiresAuth: true, roles: [0] }
            },
            {
                path: 'result',
                name: 'PaymentResult',
                component: () => import('@/views/payment/Result.vue'),
                meta: { requiresAuth: true, roles: [0] }
            },
            {
                path: 'records',
                name: 'PaymentRecords',
                component: () => import('@/views/payment/Records.vue'),
                meta: { requiresAuth: true, roles: [0, 1] }
            }
        ]
    }
]

//创建路由器
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const tokenStore = useTokenStore()
    const token = tokenStore.token
    const userRole = tokenStore.userRole

    console.log('路由守卫 - 当前路由:', to.path)
    console.log('路由守卫 - token:', token)
    console.log('路由守卫 - 用户角色:', userRole)

    // 如果是登录页面，直接放行
    if (to.path === '/login') {
        if (token) {
            next('/')
        } else {
            next()
        }
        return
    }

    // 检查是否需要认证
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!token) {
            console.log('路由守卫 - 未登录，跳转到登录页')
            ElMessage.error('请先登录')
            next('/login')
            return
        }

        // 检查角色权限
        const hasPermission = to.matched.every(record => {
            // 处理roles数组属性
            if (record.meta.roles) {
                // 如果是教师相关的路由，需要检查教师状态
                if (record.meta.requiresTeacherApproval && userRole === 1) {
                    const tokenParts = token.split('.')
                    if (tokenParts.length === 3) {
                        const payload = JSON.parse(atob(tokenParts[1]))
                        const teacherStatus = payload.claims.teacherStatus
                        // 只有审核通过的教师才能访问
                        if (teacherStatus !== 1) {
                            ElMessage.error('您的教师认证尚未通过审核，暂时无法访问该功能')
                            return false
                        }
                    }
                }
                const result = record.meta.roles.includes(Number(userRole))
                console.log('路由守卫 - 权限检查(roles):', record.path, result)
                return result
            }
            // 处理单个role属性
            else if (record.meta.role !== undefined) {
                console.log('路由守卫 - 权限检查(role):', record.path, record.meta.role === Number(userRole))
                return record.meta.role === Number(userRole)
            }
            return true
        })

        if (!hasPermission) {
            console.log('路由守卫 - 无权访问')
            ElMessage.error('无权访问该页面')
            next('/home')
            return
        }
    }

    next()
})

//导出路由
export default router
